<script setup lang="ts">
import Artplayer from "artplayer";
import {onMounted, ref} from "vue";
import Hls from 'hls.js'
import {useUserInfoStore} from "@/stores/user_info";

const userInfo = useUserInfoStore()

const props = defineProps(['id'])
const video = ref()

onMounted(() => {
  const url: any = import.meta.env.VITE_APP_SERVE + '/file/preview/video/' + props.id + "/m3u8" + '?token=' + userInfo.token.replace("Bearer ", "")

  function playM3u8(video: any, url: any, art: any) {
    if (Hls.isSupported()) {
      if (art.hls) art.hls.destroy();
      const hls = new Hls({
        xhrSetup: (xhr, url) => {
          // 修改 TS 切片文件的请求 URL
          if (url.endsWith('.ts')) {
            const fileName = new URL(url).pathname.split('/').pop();
            xhr.open('GET', import.meta.env.VITE_APP_SERVE + '/file/preview/video/' + props.id + "/" + fileName + '?token=' + userInfo.token.replace("Bearer ", ""), true);
          }
        },
      });
      hls.loadSource(url);
      hls.attachMedia(video);
      art.hls = hls;
      art.on('destroy', () => hls.destroy());
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = url;
    } else {
      art.notice.show = 'Unsupported playback format: m3u8';
    }
  }

  let art = new Artplayer({
    container: video.value,
    url: url,
    type: 'm3u8',
    customType: {
      m3u8: playM3u8,
    },
  });

  art.on('ready', () => {
    console.log('ready')
    console.info(art.hls);
  });
})
</script>

<template>
  <div class="box">
    <div class="video" ref="video"></div>
  </div>
</template>

<style scoped lang="scss">
.box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.video {
  width: 100%;
  height: 800px;
}
</style>